package com.interceptor;

import com.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author czy@win10
 * @date 2019/9/19 23:14
 * 登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		//获取请求url
		String uri = httpServletRequest.getRequestURI();
		//uri 除了登陆请求以外 其他的url 都进行拦截
		if (uri.indexOf("/login.action") >= 0) {
			return true;
		}
//        if (uri.indexOf("/register.action")>=0){
//            return true;
//        }
//        if (uri.indexOf("/signup.action")>=0){
//            return true;
//        }

		//获取session
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("USER_SESSION");
		//判断session是否有用户数据 如果有 返回true 继续向下执行
		if (user != null) {
			return true;
		}
		//不符合条件 给出提示并转发到登陆页面
		httpServletRequest.setAttribute("msg", "您还没有登陆,请先登录!");
		httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/signin.jsp").forward(httpServletRequest, httpServletResponse);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {


	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}
